// 本地刷新token，保证接口请求不过期
import axios from 'axios';

export default {

  // 获取env.js 信息
  async getEnvInfo() {
    const res = await axios({
      url: '/sdv/localApi/getEnvInfo',
    });
    const envInfo = res.data;
    return envInfo;
  },

  // 通过远程tamperMonkey工具保存到本地public_node_modules的token, tennatId, pageId信息
  async getEnvTokens() {
    const res = await axios({
      url: '/localApi/getEnvTokens',
    });
    const tokens = res && res.data;
    return tokens;
  },

  // 获取隐私协议版本号
  getPrivacyVer() {
    return new Promise(resolve => {
      axios({
        url: '/iam/uc/v1/privacyPolicyUrl?type=1&locale=zh-CN',
        method: 'get',
      })
        .then(res => {
          const privacyVer = (res.data && res.data.data && res.data.data.id) || 0;
          resolve(privacyVer);
        })
        .catch(err => {
          resolve(0);
        });
    });
  },

  // 通过登录接口获取token（需要在移动端小蜜蜂app登录时授权隐私协议，得到的token才能在pc用于其他接口连接）
  async getTokenByAppLogin(_account) {
    let account = _account;
    if (!account) {
      account = window.envInfo.envConf[window.visualEnv];
    }

    const privacyVer = await this.getPrivacyVer();
    return axios({
      url: '/iam/app/uc/app/login',
      method: 'post',
      data: {
        userName: account.userName,
        password: account.password,
        kicksflag: true,
        phoneId: '0a6fccba-3b49-4ded-80ac-e045a3d96608',
        locale: 'zh-CN',
        privacyVer,
      },
    })
      .then(res => {
        const token = res && res.data && res.data.accessToken;
        return token;
      })
      .catch(err => '');
  },

  // 获取当前用户信息
  getWho(token) {
    return axios({
      url: '/auth/who',
      method: 'get',
      headers: {
        'gc-authentication': token,
      },
    })
      .then(res => {
        const userInfo = res && res.data;
        return userInfo;
      })
      .catch(err => false);
  },
};
